package com.future.common.base;

import java.util.HashMap;
import java.util.Map;

import com.future.common.bean.Result;
import com.future.common.exception.BadRequestException;
import com.future.common.global.PlatFormContext;
import com.future.common.utils.ValidationUtil;
import com.jfinal.core.Controller;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Table;
import com.jfinal.plugin.activerecord.TableMapping;

import cn.hutool.core.bean.BeanUtil;
import lombok.extern.slf4j.Slf4j;


/**
 * controller的基类，封装一些通用的逻辑
 * 将参数相关的拦截器放到baseController上避免，减少全局的配置
 * 
 * @author Leon.Zhang
 *
 */
@Slf4j
public class BaseController extends Controller {
	private Map<String, Object> result = new HashMap<String, Object>();
	
	protected void addResult(String key, Object value){
		this.result.put(key, value);
	}
	/**
	 * 直接返回结果
	 * 
	 * @param result
	 */
	protected void renderResult(Object result) {
		Result res = new Result();
		res.set_success(true);
		res.set_message("");
		res.setResult(result);
		res.setCode("200");
		renderJson(res);
	}
	/**
	 * 返回多值的命名结果
	 * @param key
	 * @param result
	 */
	protected void renderResult() {
		if(this.result.size()==0){
			throw new RuntimeException("调用renderResult()之前需要先调用addResult");
		}
		Result res = new Result();
		res.set_success(true);
		res.set_message("");
		res.setResult(this.result);
		res.setCode("200");
		renderJson(res);
	}
	
	protected void renderResult(String key, Object result) {
		Result res = new Result();
		res.set_success(true);
		res.set_message("");
		res.setResult(Kv.by(key, result));
		res.setCode("200");
		renderJson(res);
	}


	/**
	 * 执行成功
	 */
	protected void renderSuccess() {
		Result res = new Result();
		res.set_success(true);
		res.set_message("");
		res.setResult(null);
		res.setCode("200");
		renderJson(res);
	}
	/**
	 * 从request中获取json,校验hibernate validator 注解
	 * @param type
	 * @return
	 */
	protected <T> T getJsonBody(Class<T> type) {
		return getJsonBody(type, true);
	}
	/**
	 * 获取jsonbody
	 * @param type
	 * @param validate
	 * @return
	 */
	protected <T> T getJsonBody(Class<T> type, boolean validate) {
		String jsonStr = HttpKit.readData(getRequest());
		T result = null;
		try{
			log.info("Json valuse is {}", jsonStr);
			result = JsonKit.parse(jsonStr, type);
		}catch (Exception e) {
			throw new BadRequestException("Bad Request");
		}
		if(result !=null && validate){
			ValidationUtil.checkValidation(result);
		}
		return result;
	}
	
	/**
	 * 获取当前用户的id
	 * @return
	 */
	protected String getCurrentUserId(){
		return PlatFormContext.getCurrentUser().getUserid();
	}
	/**
	 * Bean to ModelClass
	 * 
	 * @param Bean
	 * @param modelClass
	 * @return
	 */
	protected <T extends Model<T>> T beanToModel(Object Bean, Class<T> modelClass) {
		T t;
		Table table = TableMapping.me().getTable(modelClass);
		try {
			t = modelClass.newInstance();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		Map<String, Object> beanMap = BeanUtil.beanToMap(Bean);
		/**
		 * 只有当表中存在该字段的时候才会放进去，防止造成混乱
		 */
		if (beanMap != null) {
			beanMap.forEach((key, value) -> {
				if (table.getColumnNameSet().contains(key)) {
					t.set(key, value);
				}
			});
		}
		return t;
	}
}
